package com.link.base.tencent.corpwx.login.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.user.model.User;
import com.link.base.base.user.model.LoginLog;
import com.link.base.base.user.model.UserExperience;
import com.link.base.base.user.service.LoginLogService;
import com.link.base.base.user.service.UserExperienceService;
import com.link.base.base.user.service.UserService;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.login.dao.mybatis.mapper.CorpWxLoginMapper;
import com.link.base.tencent.corpwx.login.model.CorpWxUser;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.HttpRequestUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 企业微信登录服务
 * 
 * @author 欧阳振强
 * @date 2019/1/2
 */
@Service
public class CorpWxLoginServiceImpl extends BasicServiceImpl<CorpWxUser> implements CorpWxLoginService {
    @Resource
    private CorpWxLoginMapper corpWxLoginMapper;
    @Resource
    private UserService userService;
    @Resource
    private UserExperienceService userExperienceService;
    @Resource
    private AgentService agentService;
    @Resource
    private LoginLogService loginLogService;

    @Override
    public BasicMapper<CorpWxUser> getBasicMapper() throws Exception {
        return corpWxLoginMapper;
    }

    @Override
    public CorpWxUser getUserByCodeForApp(String code, String agentId) throws Exception {
        String accessToken = agentService.getExistAccessToken(agentId);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
        String param = "access_token=" + accessToken + "&code=" + code;
        String str = HttpRequestUtil.sendGet(url, param);
        JSONObject jsonObj = JSONObject.parseObject(str);
        code = jsonObj.getString("errcode");
        String zero = "0";
        if (!zero.equals(code)) {
            throw new BasicControllerException(jsonObj.getString("errmsg"));
        }
        CorpWxUser corpWxUser = new CorpWxUser();
        corpWxUser.setUserId(jsonObj.getString("UserId"));
        return corpWxUser;
    }

    @Override
    public Map<String, Object> loginByCode(String code, String agentId,String ip) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        // 根据code获取用户userId
        CorpWxUser corpWxUser = this.getUserByCodeForApp(code, agentId);
        User user;
        String username = corpWxUser.getUserId();
        if (AgentIdUtil.CORPWX_LINKGUIDE_AGENTID.equals(agentId)) {
            // 营销助手应用，暂时均使用STORE001账号登录企业微信
            username = "STORE001";
        }
        user = userService.queryByUserName(username);
        if (user == null) {
            throw new BasicServiceException("登录失败，请联系管理员！");
        }
        user.setIpAddress(ip);
        // 免密登录获取token及设置相关信息
        UserExperience userMap = userExperienceService.loginWithOutPassword(user);
        result.put("result", userMap.getUser());
        result.put("token", userMap.getToken());
        result.put("success", true);
        LoginLog record = new LoginLog();
        record.setLockFlag('N');
        record.setUserId(user.getId());
        record.setLoginName(user.getUsername());
        record.setIpAddress(ip);
        record.setUserSource("WORK_WX");
        record.setAccessToken(userMap.getToken());
        record.setLoginType("QY_WECHART");
        loginLogService.addLoginSuccessLog(record);
        return result;
    }
}
